﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Data.Helpers;
using DevExpress.Web.ASPxUploadControl;
using TheHeGeoCommercial.Dao;

namespace TheHeGeoCommercial.Admin
{
    public partial class PostNews : System.Web.UI.Page
    {
        private const string avatarPath = @"~\NewsAvatar\";
        public const string UploadNewsDirectory = "~/NewsAvatar/";
        private static UploadedFile avatarNews = null;
        private static Int32 newsId = -1;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CURRENT_USER"] == null)
                Response.Redirect("~/Admin/Login.aspx");

           
            string callRequest = Request["id"];
            if (!IsPostBack)
            {
                LoadGrvNews();
                if (!string.IsNullOrEmpty(callRequest))
                    newsId = Convert.ToInt32(callRequest);
                else
                    newsId = -1;

                if (newsId > -1)
                {
                    LoadUpdate();
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(callRequest))
                    newsId = Convert.ToInt32(callRequest);
                else
                    newsId = -1;LoadGrvNews();
            }

        }

        protected void LoadGrvNews()
        {
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var dt = (from n in ent.TinTucs
                    select new
                           {
                               n.id,
                               n.NewsTitle,
                               n.ShortView,
                               n.AvatarPath
                           }).ToList();
                Session["admin_news"] = dt;
                grvNews.DataSource = dt;
                grvNews.DataBind();
            }
            

        }
  
        protected void LoadUpdate()
        {
            try
            {
                using (var ent = new Dao.TheheGeoCommercialEntities())
                {
                    var dt = (from n in ent.TinTucs
                              where n.id == newsId
                              select n).FirstOrDefault();
                    if (dt != null)
                    {
                        txtTitle.Text = dt.NewsTitle;
                        txtShortView.Text = dt.ShortView;
                        htmlNewsEdit.Html = dt.NewsContent;
                    }
                    
                }
            }
            catch (Exception)
            {
                
                
            }

        }
        void EditNews(int rowIndex)
        {

            var _newsId = grvNews.GetRowValues(rowIndex, "id");

            DevExpress.Web.ASPxClasses.ASPxWebControl.RedirectOnCallback("~/Admin/PostNews.aspx?id=" + _newsId);

        }

        void DeleteNews(int rowIndex)
        {
            var _newsId = Convert.ToInt32(grvNews.GetRowValues(rowIndex, "id"));
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var obj = (from n in ent.TinTucs
                    where n.id == _newsId
                    select n).FirstOrDefault();
                if (obj != null)
                    ent.TinTucs.Remove(obj);
                ent.SaveChanges();
                LoadGrvNews();
            }
        }
        void AddNews(int rowIndex)
        {
            DevExpress.Web.ASPxClasses.ASPxWebControl.RedirectOnCallback("~/Admin/PostNews.aspx");
        }
        protected void grvNews_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            switch (e.ButtonID)
            {
                case "btnDelete":
                    DeleteNews(e.VisibleIndex);
                    break;

                case "btnEdit":
                    EditNews(e.VisibleIndex);
                    break;
                case "btnNew":
 
                    AddNews(e.VisibleIndex);
                    break;

            }
        }

        protected void InsertNews()
        {
            try
            {
                var newsObj = new TinTuc();
                newsObj.NewsTitle = txtTitle.Text;
                newsObj.ShortView = txtShortView.Text;
                newsObj.AvatarPath = avatarNews==null?"": avatarPath + avatarNews.FileName;
                newsObj.NewsContent = htmlNewsEdit.Html;
                using (var ent = new Dao.TheheGeoCommercialEntities())
                {
                    ent.TinTucs.Add(newsObj);
                    ent.SaveChanges();
                }
            }
            catch (Exception)
            {
                
               }
            
        }
        void SavePostedFiles(UploadedFile uploadedFile)
        {
            if (uploadedFile == null)
                return; if (!uploadedFile.IsValid) return;
            if (uploadedFile.ContentLength <= 0)
                return;
            string fileName = uploadedFile.FileName;
            var fileInfo = new FileInfo(uploadedFile.FileName);
            var newPath = Server.MapPath(UploadNewsDirectory);
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            string resFileName = newPath + fileName;

            try
            {
                uploadedFile.SaveAs(resFileName);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        protected void UpdateNews()
        {
            try
            {
                using (var ent = new Dao.TheheGeoCommercialEntities())
                {
                    var newsObj = (from n in ent.TinTucs
                              where n.id == newsId
                              select n).FirstOrDefault();
                    if (newsObj != null)
                    {
                        newsObj.NewsTitle = txtTitle.Text;
                        newsObj.ShortView = txtShortView.Text;
                        if(avatarNews!=null)
                            newsObj.AvatarPath = avatarPath + avatarNews.FileName;
                        
                        newsObj.NewsContent = htmlNewsEdit.Html;
                        ent.SaveChanges();
                    }

                }
            }
            catch (Exception)
            {


            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (newsId==-1)
                InsertNews();
            else
            {
                UpdateNews();
            }
            SavePostedFiles(avatarNews);
            Response.Redirect("~/Admin/PostNews.aspx");
        }

        protected void uploadAvatar_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
        {
            
            try
            {
                avatarNews = e.UploadedFile;
            }
            catch (Exception ex)
            {
                e.IsValid = false;
                e.ErrorText = ex.Message;
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            DevExpress.Web.ASPxClasses.ASPxWebControl.RedirectOnCallback("~/Admin/PostNews.aspx");
        }
    }
}